package com.srwl.mytx.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.alibaba.fastjson.JSONObject;
import com.bm.library.Info;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.callback.SelectCallback;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.srwl.mytx.Helper;
import com.srwl.mytx.utils.DateUtils;
import com.srwl.mytx.Constant;
import com.srwl.mytx.R;
import com.srwl.mytx.RetrofitManager;
import com.srwl.mytx.adapter.PickPictureAdapter;
import com.srwl.mytx.domain.Advertisement;
import com.srwl.mytx.domain.CommonResult;
import com.srwl.mytx.domain.FileUpLoad;
import com.srwl.mytx.domain.LiveRoom;
import com.srwl.mytx.domain.MyFile;
import com.srwl.mytx.domain.Topic;
import com.srwl.mytx.fragment.TopicFragment;
import com.srwl.mytx.parse.UserProfileManager;
import com.srwl.mytx.service.AdvertisementService;
import com.srwl.mytx.service.TopicService;
import com.srwl.mytx.utils.FileUtils;
import com.srwl.mytx.utils.GlideEngine;
import com.srwl.mytx.utils.GlideLoadUtils;
import com.srwl.mytx.utils.IMFileTools;
import com.srwl.mytx.utils.PermissionsUtils;
import com.srwl.mytx.utils.Utils;
import com.srwl.mytx.widget.ConfirmDialog;
import com.srwl.mytx.widget.PickPicturesListView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class SetAdvertisementContentActivity extends BaseActivity implements PickPictureAdapter.InteractionListener, PermissionsUtils.IPermissionsResult {

    public static void startActivity(Activity context, Advertisement advertisement,int requestCode) {

        context.startActivityForResult(new Intent(context, SetAdvertisementContentActivity.class).putExtra("advertisement", advertisement),requestCode);
    }

    private static final String TAG = "SetAdvertisement";
    private static final int REQUEST_CODE_PICTURE_CHOOSE = 1;
    private static final int REQUEST_CODE_RECORD_VIDEO = 2;
    private static final int REQUEST_CODE_SELECT_FORWARD_TOPIC = 3;
    @BindView(R.id.tv_live_room_title)
    TextView tv_liveRoomTitle;
    @BindView(R.id.tv_time)
    TextView tv_time;
    @BindView(R.id.et_forward_url)
    EditText et_forwardUrl;
    @BindView(R.id.rv_add_picture)
    PickPicturesListView picturesListView;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;
    @BindView(R.id.btn_confirm)
    Button btn_confirm;
    @BindView(R.id.rl_forward_external_url)
    RelativeLayout rl_forwardExternalUrl;
    @BindView(R.id.rl_select_forward_topic)
    View rl_forwardTopic;
    @BindView(R.id.iv_picture)
    ImageView iv_picture;
    @BindView(R.id.iv_delete)
    ImageView iv_delete;
    @BindView(R.id.tv_item_type)
    TextView tv_itemType;
    @BindView(R.id.relativeLayout)
    View ll_forwardTopic;

//非必须设置，用于广告点击后的跳转

    private Advertisement advertisement;
    private Context context;
    //视频本地路径
    private String localVideoPath;
    //服务端视频地址
    private String remoteVideoPath;
    private boolean hasVideo;
    //视频封面图片
    private String framePicPath;
    //视频大小
    private int videoSize;
    private static int PICTURE_LIMIT = 1;
    private ArrayList<MyFile> totalSelectFile = new ArrayList<>();//总的选择图片文件集合，包括本地的和远程的（历史文件）
    private ArrayList<MyFile> selectRemotePictures = new ArrayList<>();//选择的历史图片 文件
    private ArrayList<MyFile> selectRemoteVideos = new ArrayList<>();//选择的历史 视频文件
    private ArrayList<MyFile> selectLocalPictures = new ArrayList<>();//选择的本地 图片文件
    private ArrayList<MyFile> selectLocalVideos = new ArrayList<>();//选择的本地 视频文件
    private ArrayList<Photo> selectPhotos = new ArrayList<>();//本地圖片 path 集合

    private ProgressDialog progressDialog;
    private String forwardUrl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set_advertisement_content);
        ButterKnife.bind(this);
        context = this;
        advertisement = getIntent().getParcelableExtra("advertisement");

        LiveRoom liveRoom = advertisement.getLiveRoom();
        if (liveRoom != null) {
            tv_liveRoomTitle.setText(liveRoom.getTitle());
            tv_liveRoomTitle.setOnClickListener(v -> ChatRoomActivity.startActivity(this, liveRoom));
            tv_liveRoomTitle.setTextColor(getResources().getColor(R.color.btn_blue_normal));
        } else {
            tv_liveRoomTitle.setText(advertisement.getTitle());
            // TODO: 2019/10/1 应该在直播间设置一个只需传入直播间id的静态启动方法，能跳转进直播间
            //  tv_liveRoomTitle.setOnClickListener(v -> ChatRoomActivity.startActivity(this, advertisement.getrId()));
            //  tv_liveRoomTitle.setTextColor(getResources().getColor(R.color.btn_blue_normal));
        }
        tv_itemType.setText("选择主题");
        iv_delete.setVisibility(View.INVISIBLE);
        iv_delete.setImageDrawable(getDrawable(R.drawable.tx_delete_circle_blue));
        tv_time.setText(advertisement.getTime().toString());

        if (!TextUtils.isEmpty(advertisement.getVideo())) {
            MyFile remoteVideoFile = new MyFile(advertisement.getVideo(), advertisement.getPicture(), MyFile.FILE_TYPE_VIDEO, MyFile.FILE_STATUS_REMOTE);
            totalSelectFile.add(remoteVideoFile);
        } else if (!TextUtils.isEmpty(advertisement.getPicture())) {
            MyFile remotePictureFile = new MyFile(advertisement.getPicture(), MyFile.FILE_TYPE_PICTURE, MyFile.FILE_STATUS_REMOTE);
            totalSelectFile.add(remotePictureFile);
        }

        String forwardTopicId = advertisement.getForwardTopicId();
        if (!TextUtils.isEmpty(forwardTopicId)) {
            getForwardTopicDetail(forwardTopicId);
        }
        String forwardUrl = advertisement.getForwardUrl();
        if (!TextUtils.isEmpty(forwardUrl)) {
            et_forwardUrl.setText(forwardUrl);
        }


        picturesListView.init(totalSelectFile, 1, PICTURE_LIMIT, true, this);
        initForwardUrlTextChangeListener();
//        rl_forwardExternalUrl.setOnClickListener(v -> {
//            if (advertisement.getForwardTopicId() != null) {
//                showToast("设置了跳转的主题，不能再设置外部链接");
//            }
//        });
    }

    private void initForwardUrlTextChangeListener() {
        et_forwardUrl.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

//                if (advertisement.getForwardTopicId() != null) {
//                    ConfirmDialog dialog = new ConfirmDialog(SetAdvertisementContentActivity.this, "提示", "设置了跳转主题，不能再设置外部链接");
//                    dialog.show();
//                }
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
//                if (advertisement.getForwardTopicId() != null && s.toString().length() > 0) {
//                    et_forwardUrl.setText("");
//                    return;
//                }
                forwardUrl = s.toString();
                if (forwardUrl.length() != 0) {
                    ll_forwardTopic.setBackgroundColor(getResources().getColor(R.color.rp_money_bg_color));
                } else {
                    ll_forwardTopic.setBackgroundColor(getResources().getColor(R.color.yancy_grey100));
                }
            }
        });
    }


    @OnClick(R.id.tv_tips_forward_topic)
    public void tipsForwardTopic() {
        String content = "非必须设置，用于广告位点击跳转后显示的主题，跳转主题和跳转外部链接只能设置其一";
        ConfirmDialog dialog = new ConfirmDialog(context, "说明", content);
        dialog.show();
    }

    @OnClick(R.id.tv_tips_forward_external_url)
    public void tipsForwardExternalUrl() {
        String content = "非必须设置,用于广告位点击跳转的外部链接，比如是淘宝商品地址，跳转主题和跳转外部链接只能设置其一";
        ConfirmDialog dialog = new ConfirmDialog(context, "说明", content);
        dialog.show();
    }


    @OnClick(R.id.rl_select_forward_topic)
    public void selectTopic() {
        if (!TextUtils.isEmpty(forwardUrl)) {
            showToast("设置了外部链接，不能再设置跳转的主题");
            return;
        }

        startActivityForResult(new Intent(SetAdvertisementContentActivity.this, SelectForwardTopicActivity.class),REQUEST_CODE_SELECT_FORWARD_TOPIC);
//        TopicFragment topicFragment = TopicFragment.newInstance(2, UserProfileManager.getInstance().getLoginUserInfo().getuId(), true);
//        topicFragment.show(getSupportFragmentManager(), "");
//        topicFragment.setItemClickListener(new TopicFragment.ItemClickListener() {
//            @Override
//            public void onItemClick(Topic topic) {
//                advertisement.setForwardTopicId(topic.getId());
//                showSelectTopic(topic);
//                // et_forwardUrl.setEnabled(false);//当设置了跳转的topic ,让设置外部跳转链接为不可用状态
//                et_forwardUrl.setFocusable(false);
//                et_forwardUrl.setOnClickListener(v -> {
//                    showToast(et_forwardUrl, "设置了跳转主题，不能再设置外部链接");
//                });
//                //rl_forwardExternalUrl.setBackgroundColor(getResources().getColor(R.color.yancy_grey100));
//                topicFragment.dismiss();
//            }
//        });

    }

    private void showSelectTopic(Topic topic) {
        iv_delete.setVisibility(View.VISIBLE);
        String url=Utils.getTopicListPreviewUrl(topic);
        if (!iv_picture.isShown()) {
            iv_picture.setVisibility(View.VISIBLE);
        }
        //Glide.with(context).load(url).into(iv_picture);
        GlideLoadUtils.glideLoad(context, url, iv_picture);
    }

    @OnClick(R.id.iv_delete)
    public void deleteSelectTopic() {
        advertisement.setForwardTopicId(null);
        iv_delete.setVisibility(View.GONE);
        iv_picture.setVisibility(View.GONE);
        et_forwardUrl.setFocusable(true);
        et_forwardUrl.setFocusableInTouchMode(true);
        et_forwardUrl.setOnClickListener(null);

    }


    @OnClick(R.id.btn_confirm)
    public void confirm() {

//        Advertisement updateAdvertisement=new Advertisement();
//        updateAdvertisement.setId(advertisement.getId());
//        updateAdvertisement.settId(advertisement.gettId());
//        updateAdvertisement.setForwardTopicId(advertisement.getForwardTopicId());
//        updateAdvertisement.setForwardUrl(advertisement.getForwardUrl());
        if (totalSelectFile.size() == 0) {
            showToast(btn_confirm, "没有设置广告展示的内容");
            return;
        }
        String forwardUrl = et_forwardUrl.getText().toString();
        if (forwardUrl.length() != 0) {
            //判断是否是链接
            if (Utils.isHttpUrl(forwardUrl)) {
                advertisement.setForwardUrl(forwardUrl);
            } else {
                Utils.editViewValueErrorAnimate(et_forwardUrl, context);
                showToast(btn_confirm, "设置的跳转链接格式有误");
                return;
            }
        }

        FileUpLoad fileUpLoad = new FileUpLoad(context, totalSelectFile, new FileUpLoad.InteractionListener() {
            @Override
            public void onShowToast(String content) {
                showToast(btn_confirm, content);
            }

            @Override
            public void onShowProgressBar(String content) {
                showProgressDialog(content);
            }

            @Override
            public void onHideProgressBar() {
                hideProgressDialog();
            }

            @Override
            public void onUploadComplete() {
                saveToService();
            }
        });

        fileUpLoad.run();

    }

    private void saveToService() {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        showProgressDialog("正在保存...");
        final MyFile myFile = totalSelectFile.get(0);
        advertisement.setMyFile(myFile);
        String forwardUrl = advertisement.getForwardUrl();
        if (forwardUrl != null && !forwardUrl.startsWith("http://")) {
            forwardUrl = "http://" + forwardUrl;
            advertisement.setForwardUrl(forwardUrl);
        }
        if (advertisement.getUpdateCount() == null) {
            advertisement.setUpdateCount(1);
        } else {
            advertisement.setUpdateCount(advertisement.getUpdateCount() + 1);
        }
        removeShowContent();
        RetrofitManager.getInstance().createRequest(AdvertisementService.class)
                .setAdvertisement(advertisement)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {
                        hideProgressDialog();
                        CommonResult result = response.body();
                        if (!response.isSuccessful() || result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(btn_confirm, getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());

                            switch (result.getStatus()) {
                                case Constant.ADVERTISEMENT_UPDATE_LIMIT:
                                    Object expireMILLISECONDS = result.getData();
                                    String expire = "";
                                    if (expireMILLISECONDS != null) {
                                        expire = DateUtils.computeDurationTime((Integer) expireMILLISECONDS);
                                    }
                                    showToast("您还有" + expire + "才能重新设置该广告展示内容");
                                    ConfirmDialog dialog = new ConfirmDialog(SetAdvertisementContentActivity.this, "提示", "您还有" + expire + "才能重新设置该广告展示内容");
                                    dialog.show();
                                    break;
                                default:
                                    showToast(getString(R.string.system_busy));
                            }

                            return;
                        }
                        Log.d(TAG, "onResponse: 设置广告位完成");
                        //  showToast(btn_confirm, "设置广告位完成");
                        updateFileStatus(totalSelectFile);
                        setShowContent(myFile);
                        if (myFile.getType() == MyFile.FILE_TYPE_VIDEO) {
                            advertisement.setVideo(myFile.getUrl());
                            advertisement.setPicture(myFile.getVideoCover());
                        } else {
                            advertisement.setPicture(myFile.getUrl());
                        }
                        setResult(RESULT_OK, new Intent().putExtra("advertisement", advertisement));
                        ConfirmDialog confirmDialog = new ConfirmDialog(context, "提醒", "设置完成，%d秒后自动关闭", "取消", 3);
                        confirmDialog.show();
                        confirmDialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
                            @Override
                            public void confirm() {
                                confirmDialog.dismiss();
                                finish();
                            }
                        });

                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {
                        hideProgressDialog();
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    /**
     * 更新到服务端之前，需要清空之前设置的展示内容，
     * 因为展示内容是放MYfile  中上传到服务端的
     */
    private void removeShowContent() {
        advertisement.setPicture(null);
        advertisement.setVideo(null);
    }

    /**
     * 把设置的广告内容设置进advertise里面
     * setResult 中返回的advertise 对象应该携带上这些值
     *
     * @param myFile
     */
    private void setShowContent(MyFile myFile) {
        if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
            advertisement.setPicture(myFile.getUrl());
        } else {
            advertisement.setVideo(myFile.getUrl());
        }
    }

    @Override
    public void onSelectRemoteFile() {
        ArrayList<MyFile> historySelectFile = new ArrayList<>();
        historySelectFile.addAll(totalSelectFile);//添加总的
        historySelectFile.removeAll(selectLocalVideos);
        historySelectFile.removeAll(selectLocalPictures);
        MyFileSelectActivity.startActivity(this, 1 - selectLocalVideos.size(), 1 - selectLocalPictures.size(), true, historySelectFile, REQUEST_CODE_PICTURE_CHOOSE);
    }

    @Override
    public void onPickNewPicture(int position) {
//        Matisse.from(SetAdvertisementContentActivity.this)
//                .choose(MimeType.ofImage())
//                .countable(true)
//                .showSingleMediaType(true)
//                .maxSelectable(PICTURE_LIMIT)
//                .theme(R.style.choose_pictures_style)
//                // .addFilter(new (320, 320, 5 * Filter.K * Filter.K))
//                .gridExpectedSize(
//                        getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
//                .thumbnailScale(0.85f)
//                .imageEngine(new GlideEngine())
//                .forResult(REQUEST_CODE_PICTURE_CHOOSE);

        EasyPhotos.createAlbum(this, true, GlideEngine.getInstance())
                .setFileProviderAuthority("com.srbl.mytx.fileProvider")
                .setSelectedPhotos(selectPhotos)
                .setCount(PICTURE_LIMIT)
                .start(new SelectCallback() {
                    @Override
                    public void onResult(ArrayList<Photo> photos, boolean isOriginal) {
                        selectPhotos = photos;
                        totalSelectFile.removeAll(selectLocalPictures);
                        selectLocalPictures.clear();
                        for (Photo photo : photos) {
                            selectLocalPictures.add(new MyFile(photo.uri, MyFile.FILE_TYPE_PICTURE, MyFile.FILE_STATUS_LOCAL));
                        }
                        totalSelectFile.addAll(selectLocalPictures);
                        picturesListView.refresh();
                    }
                });

    }

    @Override
    public void onShowBigImage(MyFile targetFile, Info info) {

    }

    @Override
    public void onCreateVideo(View view, int position) {
        //拍摄短视频
        startRecordVideo();
    }

    @Override
    public void onShowVideo(MyFile targetVideoFile, int position) {
        //展示短视频
        showVideo(targetVideoFile.getUrl());

    }

    @Override
    public void onPictureRemove(int position, MyFile targetPictureFile) {
        if (targetPictureFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemotePictures.remove(targetPictureFile);
        } else {
            selectLocalPictures.remove(targetPictureFile);
            //清除掉已选文件记录
            for (int i = 0; i < selectPhotos.size(); i++) {
                if (selectPhotos.get(i).uri.equals(targetPictureFile.getUri())) {
                    selectPhotos.remove(i);
                    break;
                }
            }
        }
        //   bigPicturePageView.refresh();
    }

    @Override
    public void onVideoRemove(int position, MyFile targetVideoFile) {
        if (targetVideoFile.getStatus() == MyFile.FILE_STATUS_REMOTE) {
            selectRemoteVideos.remove(targetVideoFile);
        } else {
            selectLocalVideos.remove(targetVideoFile);
        }
        //  bigPicturePageView.refresh();
    }


    private void showVideo(String videoPath) {
        Uri uri = Uri.parse("http://svideo.m.taobao.com/av/implayer.html");
        Intent intent = new Intent("android.intent.action.VIEW", uri, context, MyVideoPlayActivity.class);
        intent.putExtra("localVideoPath", videoPath);
        intent.putExtra("framePicPath", framePicPath);
        intent.putExtra("videoSize", videoSize);
        startActivity(intent);
    }


    private void startRecordVideo() {
        long SDCardRemainMB = FileUtils.getSDFreeSize();
        if (SDCardRemainMB >= 0L && SDCardRemainMB < 2L) {
            showToast(getString(R.string.aliwx_no_enough_sdcard_size));
            return;
        }


        //ShortVideoKitProcesser.showRecordShortVideo(PublishTopicActivity.this, null, REQUEST_CODE_RECORD_VIDEO, SITUATION_FOR_PUBLISH, "high", 0, 0);//阿里百川短视频录制
        // startActivityForResult(new Intent(this, VideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
        // startActivityForResult(new Intent(this, FFmpegVideoRecordActivity.class), REQUEST_CODE_RECORD_VIDEO);
        VideoRecordActivityV3.startActivity(this, REQUEST_CODE_RECORD_VIDEO, true);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK || data == null) {
            return;
        }
        switch (requestCode) {
            case REQUEST_CODE_PICTURE_CHOOSE:

                ArrayList<MyFile> pictureFiles = data.getParcelableArrayListExtra("pictureFiles");
                ArrayList<MyFile> videoFiles = data.getParcelableArrayListExtra("videoFiles");
                totalSelectFile.removeAll(selectRemoteVideos);
                selectRemoteVideos.clear();
                if (videoFiles != null && videoFiles.size() != 0) {
                    selectRemoteVideos.addAll(videoFiles);
                    totalSelectFile.addAll(0, videoFiles);
                    // picturesListView.refreshVideoItem(videoFiles.get(0));
                }
                totalSelectFile.removeAll(selectRemotePictures);
                selectRemotePictures.clear();
                if (pictureFiles != null && pictureFiles.size() != 0) {
                    selectRemotePictures.addAll(pictureFiles);
                    totalSelectFile.addAll(pictureFiles);
                }
                picturesListView.refresh();

                break;
            case REQUEST_CODE_RECORD_VIDEO:
                framePicPath = data.getStringExtra("coverPath");
                localVideoPath = data.getStringExtra("videoPath");
                videoSize = data.getIntExtra("videoSize", 0);

                totalSelectFile.removeAll(selectLocalVideos);
                selectLocalVideos.clear();
                MyFile localVideoFile = new MyFile(localVideoPath, framePicPath, MyFile.FILE_TYPE_VIDEO, MyFile.FILE_STATUS_LOCAL);
                selectLocalVideos.add(localVideoFile);
                totalSelectFile.addAll(0, selectLocalVideos);//插到第一个的位置
                picturesListView.refresh();

                break;

            case REQUEST_CODE_SELECT_FORWARD_TOPIC:

                Topic topic = data.getParcelableExtra(Constant.EXTRA_INFO_TOPIC);
                advertisement.setForwardTopicId(topic.getId());
                showSelectTopic(topic);
                et_forwardUrl.setFocusable(false);
                et_forwardUrl.setOnClickListener(v -> {
                    showToast(et_forwardUrl, "设置了跳转主题，不能再设置外部链接");
                });
                break;
        }
    }


    /**
     * 保存到服务后，把已经保存的图片的状态设置为 远程图片
     * 不然连续发布，服务端把图片当成新上传图片传，插入到数据库被报ID重复的错
     *
     * @param uploadList
     */
    private void updateFileStatus(List<MyFile> uploadList) {
        for (MyFile myFile : uploadList) {
            if (myFile.getStatus() == MyFile.FILE_STATUS_UPLOAD_SUCCESS) {
                myFile.setStatus(MyFile.FILE_STATUS_REMOTE);
                //从本地文件选择集合中  移动到  远程文件选择集合中，并刷新
                if (myFile.getType() == MyFile.FILE_TYPE_PICTURE) {
                    selectLocalPictures.remove(myFile);
                    selectRemotePictures.add(myFile);
                    advertisement.setPicture(myFile.getUrl());
                } else {
                    selectLocalVideos.remove(myFile);
                    selectRemoteVideos.add(myFile);
                    advertisement.setVideo(myFile.getUrl());
                }
                picturesListView.refresh();
            }


        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        String[] permissions = new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECORD_AUDIO, Manifest.permission.CAMERA};
        PermissionsUtils.getInstance().checkPermissions(this, permissions, this);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionsUtils.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    public void onGranted() {

    }

    @Override
    public void onDenied(List<String> deniedPermissionList) {
        StringBuilder tips = new StringBuilder();
        for (String permission : deniedPermissionList) {
            if (Manifest.permission.ACCESS_FINE_LOCATION.equals(permission)) {
                tips.append("[位置] ");
            } else if (Manifest.permission.READ_EXTERNAL_STORAGE.equals(permission) || Manifest.permission.WRITE_EXTERNAL_STORAGE.equals(permission)) {
                tips.append("[储存空间] ");
            } else if (Manifest.permission.RECORD_AUDIO.equals(permission)) {
                tips.append("[麦克风] ");
            } else if (Manifest.permission.CAMERA.equals(permission)) {
                tips.append("[相机] ");
            }
        }
        ConfirmDialog dialog = new ConfirmDialog(SetAdvertisementContentActivity.this, "提醒", "使用 " + tips + "的权限被禁止，去设置？", "去设置", "取消", true);
        dialog.setConfirmListener(new ConfirmDialog.ConfirmListener() {
            @Override
            public void confirm() {
                Uri packageURI = Uri.parse("package:" + getPackageName());
                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                startActivity(intent);
            }
        });
        dialog.setCancelListener(new ConfirmDialog.CancelListener() {
            @Override
            public void cancel() {
                finish();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        dialog.show();
    }


    public void getForwardTopicDetail(final String topicId) {
        if (!Helper.getInstance().isNetworkConnected()) {
            showToast_v1(getString(R.string.network_anomalies));
            return;
        }
        RetrofitManager.getInstance().createRequest(TopicService.class)
                .getTopicFromMysql(topicId)
                .enqueue(new Callback<CommonResult>() {
                    @Override
                    public void onResponse(Call<CommonResult> call, Response<CommonResult> response) {

                        CommonResult result = response.body();
                        if (!response.isSuccessful() && result == null) {
                            Log.e(TAG, "onResponse: " + response.message());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        if (result.isError()) {
                            Log.e(TAG, "onResponse: " + result.getMsg());
                            showToast(getString(R.string.system_busy));
                            return;
                        }
                        JSONObject jsonObject = (JSONObject) result.getData();
                        Log.d(TAG, "onResponse: 查询topic完成：" + jsonObject);

                        Topic forwardTopic = jsonObject.getObject("topic", Topic.class);
                        ;//es get方法返回的对象没有id
                        showSelectTopic(forwardTopic);
                    }

                    @Override
                    public void onFailure(Call<CommonResult> call, Throwable t) {

                        showToast(getString(R.string.system_busy));
                        Log.e(TAG, "onFailure: " + t.getMessage());
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PermissionsUtils.getInstance().clear();
    }
}
